#include <QComboBox>
#include "combo-box-delegate.h"
#include "container-helper.h"

ComboBoxDelegate::ComboBoxDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QWidget* ComboBoxDelegate::createEditor (QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    QComboBox* comboBox = new QComboBox(parent);
    for (int i = 0; i < m_comboBoxData.size(); i++)
        comboBox->addItem(m_comboBoxData.at(i).first, m_comboBoxData.at(i).second);
    return comboBox;
}

void ComboBoxDelegate::setEditorData (QWidget* editor, const QModelIndex& index) const
{
    QComboBox* comboBox = qobject_cast<QComboBox*>(editor);
    m_oldValue = index.data(Qt::UserRole);

    for (int i = 0; i < comboBox->count(); i++)
    {
        QVariant item = comboBox->itemData(i);
        if (compareVariants(m_oldValue, item))
        {
            comboBox->setCurrentIndex(i);
            break;
        }
    }
}

void ComboBoxDelegate::setModelData (QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QComboBox* comboBox = static_cast<QComboBox*>(editor);
    QVariant newValue = comboBox->itemData(comboBox->currentIndex());
    if (compareVariants(m_oldValue, newValue))
        return;

    model->setData(index, newValue, Qt::UserRole);
}

const QList<QPair<QString, QVariant> > &ComboBoxDelegate::comboBoxData() const
{
    return m_comboBoxData;
}
